package chat;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;



public class Receiver extends Thread {
	ServerSocket MyService;
	Socket clientSocket = null;
	BufferedInputStream input;
	TargetDataLine targetDataLine;
	Thread captureThread;

	BufferedOutputStream out;
	  ByteArrayOutputStream byteArrayOutputStream;
	  AudioFormat audioFormat;	
	
	  SourceDataLine sourceDataLine;	  
	 byte tempBuffer[] = new byte[10000];
	 
	 Receiver() {}   
	 
     public void run () { 
    	try {
    		audioFormat = getAudioFormat();
    		DataLine.Info dataLineInfo =  new DataLine.Info( SourceDataLine.class,audioFormat);
    		
    		sourceDataLine = (SourceDataLine)
    	    AudioSystem.getLine(dataLineInfo);
    	    sourceDataLine.open(audioFormat);
    	    sourceDataLine.start();
			MyService = new ServerSocket(500);
			clientSocket = MyService.accept();
			input = new BufferedInputStream(clientSocket.getInputStream());	
			out=new BufferedOutputStream(clientSocket.getOutputStream());
			while(input.read(tempBuffer)!= -1){			
				sourceDataLine.write(tempBuffer,0,10000);
			}
		} catch (Exception e) {
			
			try {
				System.out.println ("before");
				throw e;
				
			} catch (Exception e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
			try {
				MyService.close();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
			//	e1.printStackTrace();
			}
			//e.printStackTrace();
		} 
     } 
	
	 private AudioFormat getAudioFormat(){
		    float sampleRate = 8000.0F;		  
		    int sampleSizeInBits = 16;		   
		    int channels = 1;		    
		    boolean signed = true;		    
		    boolean bigEndian = false;		 
		    return new AudioFormat(
		                      sampleRate,
		                      sampleSizeInBits,
		                      channels,
		                      signed,
		                      bigEndian);
		  }
	
	
	
	public void stopAll() {
		captureThread.stop();
		try {
			MyService.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
		//	e.printStackTrace();
		}
	}

}
